import Toast from 'toon-ui/lib/components/toast'
import  {openCamera,map,gps} from "../../../assets/js/toonModule";
import imgView from '../img-view/index'

var jsonp = require('jsonp');

export default {
  data () {
    return {
      // 页面显示
      pageShow:false ,
      // 重新编辑
      id:"",
      submit:true,
      issuePlaceholder:false,
      addPhotosParame:{
        // 图片
        photos:[],
        //
        basePhotos:[],
        // 文本内容
        content	:"",
        // 位置
        location:"",
        // 位置经纬度
        LocationCoordinate:"",
        //专题id
        subjectId:'',
      },
      //专题提示文案
      hint:'',
      curPhotoIndex:0,    //当前放大图片
      imgSwitch:false,     //图片放大开关
      picNo:0 ,        //图片编号

    }
  },
  filters: {
    // 200字符限制
    textLength:function(str){
      let length = (str+"").replace(/[\r\n]/g,"占位").length ;
      return length > 200 ? 200 : length ;
    },

  },
  mounted () {
    this.init();
  },
  //销毁实例
  deactivated(){
    this.$destroy();
  },
  methods: {

    placeholder( n ){
      this.addPhotosParame.content=this.addPhotosParame.content.replace(/[\#\＃]/g,'').replace(/[\<]/g,'＜').replace(/[\>]/g,'＞').replace(/[\;]/g,'；').replace(/[\']/g,'＇').replace(/[\"]/g,'＂').replace(/[\&]/g,'＆').replace(/[\\]/g,'＼');
   /*   if( this.addPhotosParame.content.replace(/[*]/g,'-').replace(/[\n\r]/g,'**').length>200 ){
        var newContent = this.addPhotosParame.content.replace(/\*\*!/g,"-").replace(/[\r\n]/g,"占位").substr(0,200);

        // 文本替换
        this.addPhotosParame.content = this.addPhotosParame.content.substr(0, newContent.replace(/[\r\n]/g,"占位").length) ;
      }*/


      var newContent = this.addPhotosParame.content.replace(/[*]/g,'-').replace(/[\n\r]/g,'**');
      if(newContent.length>200){
        newContent = newContent.substring(0,200);
        newContent = newContent.replace(/\*\*/g,'-').replace(/\*$/,'');
        this.addPhotosParame.content = this.addPhotosParame.content.substring(0,newContent.length);
      }

      // this.addPhotosParame.content = this.addPhotosParame.content.substr(0, 200 - this.addPhotosParame.content.replace(/[\r\n]/g,"占位").length + 200) ;
      this.issuePlaceholder = n ;
    },
    //初始化
    init(){
      this.$util.setTitle("随手拍");


      if(this.$route.query && this.$route.query.hint !='null'){
        this.hint = this.$route.query.hint;
      }
      if(this.$route.query && this.$route.query.subjectId !='null'){
        this.addPhotosParame.subjectId = this.$route.query.subjectId;
      }

      //this.toonGPS();
      this.addPhotosParame =  window.GLOBLEDATE_addPhotosParame ||  this.addPhotosParame  ;
      if(this.$util.GData( "addPhotosParame")){
        this.addPhotosParame = this.$util.GData( "addPhotosParame") ;
        this.$util.GData( "addPhotosParame" , false) ;
        this.pageShow = true ;
      }else{
        this.queryPhotoDetailById(this.$util.getQueryStringHr("id"))
      }
    },
    queryPhotoDetailById:function(id){
      if(!id){
        return this.pageShow  =true ;
      }
      this.id = id ;
      let _this=this;
      var params={
        "id":id
      };
      if(!this.toonNETWORK()){ return }
      this.$http.post("/convphoto/queryPhotoDetailById",params).then(function(res){
        if (res.meta && res.meta.code != 0){
          Toast({
            message: res.meta.message,
            duration: 1000, // 持续时间，默认3000毫秒
          });
          return false ;
        }
        var datas = res.data || {};
        if(datas.auditCode&&datas.auditCode==2){
          var datasCope = JSON.stringify(datas) ;
          datasCope = eval("("+datasCope+")");
          _this.addPhotosParame = {
            photos:datas.photos,
            basePhotos: datasCope.photos ,
            content	:datas.content,
            location:datas.location,
            LocationCoordinate:datas.LocationCoordinate
          }
          return _this.pageShow  =true ;
        }else{
          _this.$util.GData("detail",datas)
          if(datas.auditCode == 3 && datas.dealStatus){
            _this.goDetail(_this.id  , 2 ) ;
          }else{
            _this.goDetail(_this.id  , 1 ) ;
          }
        }
      }).catch(function (err) {
        // Toast({
        //   'message': '获取详情失败',
        //   'duration': 1000, // 持续时间，默认3000毫秒
        // });
      })
    },
    //添加随手拍
    issue(){
      let _this  = this  ;
      _this.addPhotosParame.content = _this.addPhotosParame.content.trim();
      if(!(_this.addPhotosParame.content).trim()) {
        Toast({
          message: '请填写您要发布的内容！',
          duration: 2000, // 持续时间，默认3000毫秒
        });
        return false
      }
      if(_this.addPhotosParame.content .length<4  ){
        Toast({
          message: '内容至少4个字符或汉字',
          duration: 2000, // 持续时间，默认3000毫秒
        });
        return false
      }
      if(_this.addPhotosParame.photos.length<1){
        Toast({
          message: '请上传您要发布的照片！',
          duration: 2000, // 持续时间，默认3000毫秒
        });
        return false
      }
      if(!_this.addPhotosParame.location){
        Toast({
          message: '请选择事情所在位置！',
          duration: 2000, // 持续时间，默认3000毫秒
        });
        return false
      }
      _this.addPhotosParame.photos = _this.addPhotosParame.photos.sort(function(a,b){return a.No - b.No});
      let param = {
        photos:_this.addPhotosParame.photos,
        content	:_this.addPhotosParame.content.replace(/[\r\n]{3,}/g,'\r\n\r\n').replace(/[\r\n]$/g,''),
        location:_this.addPhotosParame.location,
        subjectId:_this.addPhotosParame.subjectId,
      }
      _this.addPhotos(param)
    },

    addPhotos(param){
      for(var i in this.addPhotosParame.basePhotos){
        if(this.addPhotosParame.basePhotos[i].mask){
          return
        }
      }
      if(!this.toonNETWORK()){ return }
      let _this  = this ,
        url =  '/convphoto/addPhotos'  , id = _this.$util.getQueryStringHr("id") || "" ;
      if( id ){
        url =  '/convphoto/updatePhotos' ;
        param.id= id ;
      }
      if(_this.submit){
        _this.submit = false ;
        this.$http.post(url,param)
          .then(function (res) {
            if(res.meta.code!=0){
              Toast({
                message: '发布失败，请稍后重试！',
                duration: 2000, // 持续时间，默认3000毫秒
              });
              _this.submit = true  ;
              return false ;
            }
            // //成功后跳转至列表页面
            // Toast({
            //   message: '发布成功',
            //   duration:1000, // 持续时间，默认3000毫秒
            //   iconClass: 'toast-icon icon-success' // 上方显示icon图标，图标需自行准备
            // });
            Toast({
              message: '发布成功，客服正在审核中，请耐心等待...',
              duration:1000
            })
            setTimeout(function(){
              _this.goList( "list" )
            },1000)
          })
          .catch(function (err) {
            // Toast({
            //   message: '发布失败，请稍后重试！',
            //   duration: 2000, // 持续时间，默认3000毫秒
            // });
            _this.submit = true  ;
          });
      }

    },
    //删除一张涂片
    delPhoto(index){
      let _this = this,convid = _this.$util.getQueryStringHr("id") || "" ;
      if(convid){
        //编辑页
        _this.addPhotosParame.photos.splice(index,1);
        _this.addPhotosParame.basePhotos.splice(index,1)
      }else{
        //新发布页
        for(var j=0; j<_this.addPhotosParame.photos.length; j++){
          if(_this.addPhotosParame.basePhotos[index].id == _this.addPhotosParame.photos[j].No){
            _this.addPhotosParame.photos.splice(j,1);
            _this.addPhotosParame.basePhotos.splice(index,1)
          }
        }
      }



    },
    //调用通相机
    toonOpenCamera(item){
        if(!this.toonNETWORK()){ return}
        let _this = this ;
        let leftImgCount = parseInt(6) - parseInt(_this.addPhotosParame.basePhotos.length);
        openCamera(function(res){
            if( Array.isArray(res) ){
              for(var i in  res ){
                if( _this.addPhotosParame.basePhotos.length >= 6){
                  Toast({
                    message: '你最多只能上传6张图片',
                    duration: 1000, // 持续时间，默认3000毫秒
                  });
                  return
                }
                //记录编号
                _this.picNo += 1;
                _this.addPhotosParame.basePhotos.push({
                  fileUrl:"data:image/png;base64,"+res[i].base64 ,
                  mask:true,
                  id:_this.picNo,
                });
                //开始上传
                _this.uploadAttachment( ".png",res[i].base64,_this.picNo)
              }
            }else{
              if( _this.addPhotosParame.basePhotos.length >= 6){
                Toast({
                  message: '你最多只能上传6张图片',
                  duration: 1000, // 持续时间，默认3000毫秒
                });
                return
              }
              //记录编号
              _this.picNo += 1;
              _this.addPhotosParame.basePhotos.push({
                fileUrl:"data:image/png;base64,"+res.base64,
                mask:true,
                id:_this.picNo,
              });
              _this.uploadAttachment( ".png",res.base64,_this.picNo)
            }
        },function(){},{"maxCount":leftImgCount})

    },
    //上传图片
    uploadAttachment(fileType,fileStream,id){
      let  _this =this   , params =[{ fileType: fileType ,fileStream:fileStream}];
      this.$http.post( '/convphoto/uploadAttachment',params)
        .then(function (res) {
          if(res.meta && res.meta.code == '0'){
            _this.addPhotosParame.photos.push({
              fileUrl:res.data[0].fileUrl,
              No:id,
            });
            //去掉图片上的遮罩层
            for(var j=0; j<_this.addPhotosParame.basePhotos.length; j++){
              if(_this.addPhotosParame.basePhotos[j].id == id){
                _this.addPhotosParame.basePhotos[j].mask=false;
              }
            }
          }else{
            Toast({
              message: '上传失败请重试',
              duration: 1000, // 持续时间，默认3000毫秒
              iconClass: 'toast-icon icon-fail' // 上方显示icon图标，图标需自行准备
            });
            //开始上传
            for(var j=0; j<_this.addPhotosParame.basePhotos.length; j++){
              if(_this.addPhotosParame.basePhotos[j].id == id){
                _this.addPhotosParame.basePhotos.splice(j,1);
              }
            }

          }
        })
        .catch(function (err) {
          Toast({
            message: '上传失败请重试',
            duration: 1000, // 持续时间，默认3000毫秒
            iconClass: 'toast-icon icon-fail' // 上方显示icon图标，图标需自行准备
          });
          //开始上传
          //_this.addPhotosParame.basePhotos.pop();
          for(var j=0; j<_this.addPhotosParame.basePhotos.length; j++){
            if(_this.addPhotosParame.basePhotos[j].id == id){
              _this.addPhotosParame.basePhotos.splice(j,1);
            }
          }
        });
    },
    //调用GPS获取位置
    toonGPS(){
      let _this = this ;
      gps(function(res){
        _this.addPhotosParame.LocationCoordinate = res.data.latitude  +  "," + res.data.longitude;
        _this.lbsAMap();
      })
    },
    //调用百度地图
    lbsAMap(){
      // 百度地图API功能

      let http = "http:" , _this = this;
      if(location.href.indexOf("https:") >=0 ){
        http="https:"
      }
      jsonp(http+'//api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='+_this.addPhotosParame.LocationCoordinate+'&output=json&pois=addr&ak=vl9INV8fb81l9EiatxyG3n2O4I7PGUra',{}, function (err, data) {

        if (err) {
        } else if(data.result && data.result.formatted_address){

          _this.addPhotosParame.location = data.result.formatted_address ;
        }
      });

    },
    //调用map获取位置
    toonMAP(){
      let _this  = this
      map( false ,function(res){
        if(! res.data || ! res.data.address ){return}
        _this.addPhotosParame.location  = res.data.address;
        _this.addPhotosParame.LocationCoordinate = res.data.latitude +  "," + res.data.longitude;
      })
    },
    toonNETWORK(){
      if( navigator.onLine ){
        return true
      }
      Toast({
        message: '无网络连接，请稍后重试',
        duration: 1000, // 持续时间，默认3000毫秒
      });
      return false
    },
    //跳转到我的列表
    goDetail: function ( id  , type) {

      console.log(type)
      switch (type){
        case 1:
          this.$router.replace({
            name: 'detailPraising',
            params:{id:id},
            query:{index:0}
          });
          break;
        case 2:
          this.$router.replace({
            name: 'detailReport',
            params:{id:id},
            query:{index:0}
          });
          break;
      }

    },
    //跳转到我的列表
    goList: function ( list ) {
      this.$util.GData(false)
      if(list=="list"){
        this.$router.replace({
          name: 'list'
        });
      }else{
        this.$router.push({
          name: 'list'
        });
      }
    },
    bigImg:function( index ){
      // this.$util.GData( "addPhotosParame" , this.addPhotosParame);
      // this.$router.push({
      //   name: 'imgView',
      //   params:{
      //     url:this.addPhotosParame.photos[ index ].fileUrl
      //   },
      //   query : {
      //     title :"随手拍"
      //   }
      // });
      this.curPhotoIndex=index;
      this.imgSwitch=true;
    },
    reset(){
      this.curPhotoIndex=-1;
    }
    //xss防注入
    /*
     characterTransform(str){
     alert(this.addPhotosParame.content);
     this.addPhotosParame.content=this.addPhotosParame.content.replace(/[\#\＃]/g,'').replace(/[\<]/g,'＜').replace(/[\>]/g,'＞').replace(/[\;]/g,'；').replace(/[\']/g,'＇').replace(/[\"]/g,'＂').replace(/[\&]/g,'＆').replace(/[\\]/g,'＼');
     //return str;
     }*/
  },
  components: {
    imgView
  },

}
